﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Event_SG_EWDT
{
    public partial class InvitePplToGroup : System.Web.UI.Page
    {
        string groupID = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            groupID = Request.QueryString["groupid"];

            if (Session["Member"] == null || groupID == "")
            {
                Session["flag"] = "redirecterror";
                Response.Redirect("~/registration.aspx");
            }
        }

        protected void btnInviteToGroup_Click(object sender, EventArgs e)
        {
            if (tbxInviteToGroupEmail.Text == "")
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "toast", "$().toastmessage('showErrorToast', 'Opps! One or more required fields were left empty');", true);
                return;
            }

            int error = 0;

            try
            {
                Group g = GroupControl.RetrieveGroup(groupID);

                if (g.GroupId != null)
                {
                    string groupName = g.GroupName;

                    String[] address = tbxInviteToGroupEmail.Text.Split(new char[] { ';' });

                    foreach (string a in address)
                    {
                        if (!MemberControls.IsAccountExist(a) && a != "")
                        {
                            Utility.EmailJoinEventMessage(Request, groupName, groupID, a);
                        }
                        else
                        {
                            int s = Convert.ToInt32(Session["Member"]);
                            int r = Convert.ToInt32(MemberControls.RetrieveMemberByAccount(a).MembershipNo);
                            GroupControl.CreateMemberGroup(r.ToString(), groupID.ToString(), "Member", 0);
                            Utility.SendNotificationForGroupInvite(Request, groupID, s, r);
                        }
                    }
                }
                else
                {
                    error = 100;
                }
            }
            catch
            {
            }
            finally
            {
                if (error == 0)
                {
                    Session["flag"] = "invited";
                    Response.Redirect("~/ViewGroup.aspx?groupid=" + groupID);
                }
                else if (error == 100)
                {
                    Session["flag"] = "notfound";
                    Response.Redirect("~/index.aspx");
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "toast", "$().toastmessage('showErrorToast', 'Opps! One of more emails were invalid!');", true);
                }
            }
        }
    }
}